package com.yanlight.app.service.impl;

import com.yanlight.app.dal.dao.ApplyMoneyDAO;
import com.yanlight.app.dal.dao.WxMsgReceiverDAO;
import com.yanlight.app.dal.entity.ApplyMoney;
import com.yanlight.app.dal.entity.WxMsgReceiver;
import com.yanlight.app.service.ApplyMoneyService;
import com.yanlight.exception.ErrorType;
import com.yanlight.support.http.Response;
import com.yanlight.support.wx.WxConstants;
import com.yanlight.util.DateTimeUtil;
import com.yanlight.util.ResponseUtil;
import com.yanlight.util.WxHttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApplyMoneyServiceImpl implements ApplyMoneyService {

    @Autowired
    ApplyMoneyDAO applyMoneyDAO;

    @Autowired
    WxMsgReceiverDAO wxMsgReceiverDAO;

    @Override
    public Response save(ApplyMoney applyMoney) {

        applyMoney.setApplyTime(DateTimeUtil.getNowTime());
        int save = applyMoneyDAO.save(applyMoney);

        if (save > 0) {
            //发送微信通知
            List<WxMsgReceiver> wxMsgReceivers = wxMsgReceiverDAO.noticeList();
            if (wxMsgReceivers != null && wxMsgReceivers.size() > 0) {
                wxMsgReceivers.forEach(item -> {
                    if (!StringUtils.isBlank(item.getOpenId())) {
                        WxHttpClientUtil.applyMoneyMessage(item.getOpenId(), WxConstants.applyMoneyCallOperate + applyMoney.getId());
                    }
                });
            }

            if (applyMoney.getCompanyId() == 100) {
                //给特定商家推送消息
            }

            return ResponseUtil.success(applyMoney.getId());
        } else {
            return ResponseUtil.fail(ErrorType.SYSTEM_ERROR);
        }
    }

    @Override
    public Response queryById(Integer applyId) {
        ApplyMoney byId = applyMoneyDAO.findById(applyId);
        if (byId == null) {
            return ResponseUtil.fail(ErrorType.NOT_EXIST_RECORD);
        }
        return ResponseUtil.success(byId);
    }

}
